<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表监控管理页面</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f9f9f9;
            margin: 0;
            padding: 0;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        /* 表格容器样式 */
        .table-container {
            max-height: 90%; /* 固定表格最大高度 */
            overflow-y: auto; /* 启用竖向滚动条 */
            overflow-x: hidden; /* 禁用横向滚动条 */
            border: 1px solid #ddd; /* 添加边框，区分滚动区域 */
            border-radius: 8px;
            box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1); /* 内部阴影增强视觉 */
        }

        /* 表头固定效果 */
        table {
            border-collapse: collapse;
            width: 100%;
        }

        th {
            position: sticky;
            top: 0;
            background-color: #f4f4f4;
            z-index: 1;
            box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1); /* 添加阴影区分表头 */
        }

        .container {
            margin: 10px auto;
            height: 95%;
            width: 90%;
            max-width: 1200px;
            background-color: #fff;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            padding: 30px;
            box-sizing: border-box;
        }

        .actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .actions button {
            padding: 8px 15px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            font-size: 14px;
            margin-right: 10px;
        }

        .actions button:last-child {
            margin-right: 0;
        }

        .actions button:hover {
            background-color: #0056b3;
        }

        .billing-container {
            display: flex;
            gap: 30px;
            align-items: center;
        }

        .billing-box {
            padding: 15px 25px;
            background-color: #f4f4f4;
            border-radius: 10px;
            border: 2px solid #ddd;
            font-weight: 600;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 200px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 14px 18px;
            text-align: center;
            border: 1px solid #ddd;
            font-size: 14px;
        }

        th {
            background-color: #f4f4f4;
            font-weight: bold;
            color: #333;
        }

        tbody tr:hover {
            background-color: #fafafa;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background-color: #fff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            width: 380px;
            max-width: 90%;
            animation: modalFadeIn 0.3s ease-out;
        }

        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            font-size: 1.6em;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            text-align: center;
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
        }

        .modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 20px;
        }

        .modal-actions button {
            padding: 12px 25px;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.2s ease;
            cursor: pointer;
            font-size: 15px;
        }

        .modal-actions button[type="button"] {
            background-color: #f0f0f0;
            color: #666;
            display: inline-block;
            float: none;
        }

        .modal-actions button[type="button"]:hover {
            background-color: #e0e0e0;
        }

        .modal-actions button[type="submit"] {
            background-color: #007BFF;
            color: white;
        }

        .modal-actions button[type="submit"]:hover {
            background-color: #0069d9;
            transform: translateY(-1px);
        }

        /* 新增表单输入框样式 */
        input,
        select {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }

        /* 弹窗中的输入框聚焦样式 */
        input:focus,
        select:focus {
            outline: none;
            border-color: #007BFF;
        }

        /* 更新表格操作按钮样式 */
        td button {
            padding: 8px 12px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            font-size: 14px;
            margin-right: 5px;
        }

        td button:last-child {
            margin-right: 0;
        }

        td button:hover {
            background-color: #0056b3;
        }

        /* 添加操作列的特定样式 */
        td:last-child {
            width: 120px; /* 设置操作列的宽度 */
        }

        /* 新增按钮组样式 */
        .button-group {
            display: flex;
            gap: 10px; /* 按钮之间的间距 */
            white-space: nowrap; /* 防止文字换行 */
        }


    </style>

    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

<body>
<div class="container">
    <div class="actions">
        <button id="createTableBtn">新建表</button>
        <div class="billing-container">
            <div class="billing-box">
                <span id="refreshNum">流量计费：0</span>
            </div>
            <div class="billing-box">
                <span id="incrementNum">次数计费：0</span>
            </div>
        </div>
    </div>

    <div class="table-container">
        <table>
            <thead>
            <tr>
                <th>表ID</th>
                <th>名称</th>
                <th>类型</th>
                <th>监控ID</th>
                <th>识别值</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="tableBody"></tbody>
        </table>
    </div>

</div>

<!-- 新建表弹窗 -->
<div class="modal" id="createTableModal">
    <div class="modal-content">
        <div class="modal-header">新建表</div>
        <form id="createTableForm">
            <label for="tableAlias">别名：</label>
            <input type="text" id="tableAlias" required><br><br>
            <label for="tableType">类型：</label>
            <select id="tableType" required>
                <option value="Ammeter">电表</option>
                <option value="LevelMeter">液位计</option>
                <option value="PressureMeter">压力表</option>
                <option value="TemperatureMeter">温度表</option>
                <option value="WaterMeter">水表</option>
                <option value="ElectronicScale">电子表</option>
            </select><br><br>
            <div class="modal-actions">
                <button type="button" class="closeModal" data-target="createTableModal">取消</button>
                <button type="submit">提交</button>
            </div>
        </form>
    </div>
</div>

<!-- 新建监控弹窗 -->
<div class="modal" id="createMonitorModal">
    <div class="modal-content">
        <div class="modal-header">新建监控</div>
        <form id="createMonitorForm">
            <label for="monitorId">监控ID：</label>
            <input type="text" id="monitorId" required><br><br>
            <input type="hidden" id="monitormeterId">
            <div class="modal-actions">
                <button type="button" class="closeModal" data-target="createMonitorModal">取消</button>
                <button type="submit">提交</button>
            </div>
        </form>
    </div>
</div>

<!-- 弹窗内容 -->
<div class="modal" id="viewImageModal">
    <div class="modal-content">
        <div class="modal-header">查看实况</div>
        <img id="imageDisplay" src="" alt="图片加载中..." style="width: 100%; height: auto; border-radius: 8px;">
        <div class="modal-actions">
            <button type="button" class="closeModal" data-target="viewImageModal">关闭</button>
        </div>
    </div>
</div>


<script>
    const API_BASE = '/api';

    // 获取所有表格数据
    async function fetchTableData() {
        try {
            const response = await axios.get(`${API_BASE}/getAllTableInfo`);
            if (Array.isArray(response.data)) {
                renderTable(response.data);
            } else {
                console.error('获取的数据不是一个有效的数组:', response.data.data);
                renderTable([]);
            }
        } catch (error) {
            console.error('Error fetching table data:', error);
        }
    }

    // 获取增量信息
    async function fetchIncrementInfo() {
        try {
            const response = await axios.get(`${API_BASE}/getIncrement`);
            document.getElementById('refreshNum').innerText = `流量计费：${response.data.refresh_num}`;
            document.getElementById('incrementNum').innerText = `次数计费：${response.data.increment_num}`;
        } catch (error) {
            console.error('Error fetching increment info:', error);
        }
    }

    // 渲染表格数据
    function renderTable(rows) {
        const tableBody = document.getElementById('tableBody');
        tableBody.innerHTML = '';

        // 定义类别映射
        const typeMapping = {
            Ammeter: '电表',
            LevelMeter: '液位计',
            PressureMeter: '压力表',
            TemperatureMeter: '温度表',
            WaterMeter: '水表',
            ElectronicScale: "电子表"
        };

        rows.forEach(row => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                    <td>${row.id}</td>
                    <td>${row.alias}</td>
                    <td>${typeMapping[row.type] || row.type}</td>
                    <td>${row.monitorId || '无'}</td>
                    <td>${row.aiValue || '无'}</td>
                    <td>
                        <div class="button-group">
                            <button onclick="showCreateMonitorModal('${row.id}')">新建</button>
                            <button onclick="viewImage('${row.monitorId}')">查看</button>
                            <button onclick="refreshTableInfo('${row.id}')">刷新</button>
                        </div>
                    </td>
                `;
            tableBody.appendChild(tr);
        });
    }

    // 创建新表
    async function createTable() {
        const alias = document.getElementById('tableAlias').value;
        const type = document.getElementById('tableType').value;
        try {
            await axios.post(`${API_BASE}/createTable`, { alias, type });
            await fetchTableData();
            document.getElementById('createTableForm').reset();
        } catch (error) {
            console.error('Error creating table:', error);
        }
    }

    // 查看图片
    async function viewImage(monitorId) {
        const imageDisplay = document.getElementById('imageDisplay');
        const modal = document.getElementById('viewImageModal');
        modal.classList.add('active');
        try {

            const response = await axios.get(`${API_BASE}/getImage`, { params: { monitor_id: monitorId } });
            const imageUrl = response.data;
            if (imageUrl==null){
                imageDisplay.alt = "设备未开始记录"
            }else if(imageUrl){
                imageDisplay.src = response.data.imageUrl;
            }  else {
                imageDisplay.alt = "图片加载失败，请稍后重试！"
            }
        } catch (error) {
            console.error('Error fetching image:', error);
            imageDisplay.src = ""; // 重置为默认状态

        }
    }

    // 关闭弹窗
    function closeModal(modalId) {
        const modal = document.getElementById(modalId);
        modal.classList.remove('active');

        if (modalId === 'viewImageModal') {
            const imageDisplay = document.getElementById('imageDisplay');
            imageDisplay.src = ""; // 重置图片为默认状态
        }
    }

    // 创建监控
    async function createMonitor() {
        const monitorId = document.getElementById('monitorId').value;
        const meterId = document.getElementById('monitormeterId').value;
        try {
            await axios.post(`${API_BASE}/createMonitor`, { monitor_id: monitorId, meter_id: meterId });
            await fetchTableData();
            document.getElementById('createMonitorForm').reset();
        } catch (error) {
            console.error('Error creating monitor:', error);
        }
    }

    // 刷新表格信息
    async function refreshTableInfo(meter_id) {
        try {
            await axios.post(`${API_BASE}/getTableInfo`, { meter_id });
            await fetchIncrementInfo();
        } catch (error) {
            console.error('Error refreshing table info:', error);
        }
    }

    // 显示创建监控的弹窗
    function showCreateMonitorModal(meterId) {
        document.getElementById('monitormeterId').value = meterId;
        document.getElementById('createMonitorModal').classList.add('active');
    }

    // 绑定事件
    function bindEvent(selector, event, handler) {
        document.querySelector(selector).addEventListener(event, handler);
    }

    // 绑定表单提交事件
    bindEvent('#createTableForm', 'submit', event => {
        event.preventDefault();
        createTable();
        closeModal('createTableModal');
    });

    bindEvent('#createMonitorForm', 'submit', event => {
        event.preventDefault();
        createMonitor();
        closeModal('createMonitorModal');
    });

    // 绑定按钮点击事件
    bindEvent('#createTableBtn', 'click', () => {
        document.getElementById('createTableModal').classList.add('active');
    });

    document.querySelectorAll('.closeModal').forEach(button => {
        button.addEventListener('click', event => {
            closeModal(event.target.dataset.target);
        });
    });

    // 初始化数据
    fetchTableData();
    fetchIncrementInfo();
</script>
</body>

</html>
